package com.hy.wsroom.handler;

import com.hy.wsroom.entity.Message;
import com.hy.wsroom.enums.MessageTypeEnum;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Component
public class MessageHandlerManager {
    private final Map<String, MessageHandler> messageHandlerMap = new HashMap<>();

    public MessageHandlerManager(@Autowired List<MessageHandler> handlerList) {
        handlerList.forEach(handler -> messageHandlerMap.put(handler.getType().getType(), handler));
    }

    public MessageHandler getMessageHandler(String type) {
        return messageHandlerMap.get(type);
    }

    public void handle(Message message) throws Exception {

        MessageHandler messageHandler = getMessageHandler(message.getType());
        if (messageHandler == null) {
            messageHandler = getMessageHandler(MessageTypeEnum.UNSUPPORTED.getType());
        }
        messageHandler.handle(message);
    }

}
